<template>
  <el-tooltip
    :disabled="!isTruncated"
    :content="fullText"
    placement="top"
    :open-delay="300"
  >
    <span
      ref="textRef"
      class="truncated-text"
      :style="{
        maxWidth: `${width}px`,
      }"
      @mouseenter="checkTruncation"
    >
      <slot v-if="$slots.default">
        {{ fullText }}
      </slot>
      <template v-else>
        {{ fullText }}
      </template>
    </span>
  </el-tooltip>
</template>

<script>
import { ref, onMounted, computed, defineComponent } from "vue";

export default defineComponent({
  name: "TruncatedText",
  props: {
    text: {
      type: String,
      default: "",
    },
    width: {
      type: Number,
      default: 120,
    },
  },
  setup(props) {
    const textRef = ref(null);
    const isTruncated = ref(false);
    const fullText = computed(() => props.text);

    const checkTruncation = () => {
      if (textRef.value) {
        isTruncated.value = textRef.value.scrollWidth > textRef.value.clientWidth;
      }
    };
    return {
      textRef,
      isTruncated,
      fullText,
      checkTruncation,
    };
  },
});
</script>

<style scoped>
.truncated-text {
  display: inline-block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
